<template>
    <div class="content-box vpn-container">
        <div class="page-header">
            <div class="page-tit">
                设备列表
            </div>
        </div>

        <div class="user-l" v-loading="isLoading">
            <div class="item" v-for="(item, k) in tableData">
                <div class="img">
                    <img :src="`data:image/jpeg;base64,${item.last_frame_base64}`" alt="item.user_id" v-if="item.last_frame_base64">
                    <div class="color-success" v-else>暂无预览图</div>
                </div>
                <div>
                    <div>用户：{{ item.user_id }}</div>
                    <div>屏幕：{{ item.screens.length }}个</div>
                    <div>在线：{{ item.online ? `在线` : '离线' }}</div>
                    <div>状态：{{ item.control_by ? `${item.control_by}正在使用` : '空闲' }}</div>
                </div>
                <div class="control">
                    <el-button type="primary" @click="startShare(item)" v-if="!currentItem || currentItem.user_id != item.user_id">控制
                    </el-button>
                    <el-button type="danger" @click="stopShare(item)" v-if="currentItem && currentItem.user_id == item.user_id">
                        结束
                    </el-button>
                </div>
            </div>
        </div>

        <el-dialog append-to-body v-model="showScreen" title="远程控制" :close-on-click-modal="false" width="95%" @close="closeDialog" top="10px">
            <div class="show-screen" ref="screenRef" @mouseenter="mouseInHandle" @mouseleave="mouseOutHandle" @mousedown="handleClick">
                <img class="screen" :src="screenImg" alt="共享" v-if="screenImg">
            </div>
            <div slot="footer">
                <el-form class="edit-form">
                    <el-form-item label="屏幕:">
                        <el-radio-group v-model="currentItem.display_current" placeholder="请选择屏幕" @change="changeScreen">
                            <el-radio v-for="(sc, i) in currentItem.screens" :label="`屏幕[${sc.index}]${sc.width}X${sc.height}`" :value="sc.index"></el-radio>
                        </el-radio-group>
                    </el-form-item>
                    <el-form-item label="帧率:">
                        <el-radio-group v-model="currentItem.fps" placeholder="请选择帧率" @change="changeFPS">
                            <el-radio v-for="(f, i) in fpsArr" :label="`${f}`" :value="f"></el-radio>
                        </el-radio-group>
                    </el-form-item>
                    <el-form-item label="质量:">
                        <el-radio-group v-model="currentItem.quality" placeholder="请选择质量" @change="changeQuality">
                            <el-radio v-for="(f, i) in qualityArr" :label="`${f}`" :value="f"></el-radio>
                        </el-radio-group>
                    </el-form-item>
                </el-form>
            </div>
        </el-dialog>

    </div>
</template>

<script setup>
import {onMounted, onUnmounted, ref} from "vue";
import {listVpnApi, startVpnApi} from "../../api/api";
import {ElMessage} from "element-plus";
import {onBeforeRouteLeave} from "vue-router";

const tableData = ref([])
const screenImg = ref(null)
const mouseIN = ref(false)
const isLoading = ref(false)
const showScreen = ref(false)
const currentItem = ref(null)
const screenRef = ref(null)
const fpsArr = ref([1, 2, 3, 4, 5, 6, 10, 12, 15, 20, 30])
const qualityArr = ref([5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 60, 70, 80, 90, 100])

let timer = null;

const userId = window.electronAPI.store.get("user_id")
console.log("userId:", userId)

const ws = ref(null)
const wsSendCmd = ref(null)

const status = ref('未连接')
const isConnected = ref(false)


const handleClick = (event) => {
    // 0 左键 1中键  2右键
    if (event.button === 2) {
        event.preventDefault();
    }
    mouseControl(event.offsetX, event.offsetY, event.button == 0 ? "left" : "right");
}

const mouseInHandle = () => {
    mouseIN.value = true;
}

const mouseOutHandle = () => {
    mouseIN.value = false;
}

const mouseControl = (offsetX, offsetY, button) => {
    let divWidth = screenRef.value.getBoundingClientRect().width,
        divHeight = screenRef.value.getBoundingClientRect().height,
        screen = currentItem.value.screens[currentItem.value.display_current];
    console.log('点击位置:', offsetX, offsetY);

    let x = parseInt(screen.width * offsetX / divWidth),
        y = parseInt(screen.height * offsetY / divHeight);
    console.log('实际位置:', x, y);

    wsSendCmd.value.send(JSON.stringify({type: "mouseclick", key: button, x: x, y: y}))
}

// 修改屏幕
const changeScreen = (v) => {
    if (!wsSendCmd.value) return ElMessage.error("未启动");
    wsSendCmd.value.send(JSON.stringify({type: "screen", key: String(v)}))
}

// 修改FPS
const changeFPS = (v) => {
    if (!wsSendCmd.value) return ElMessage.error("未启动");
    wsSendCmd.value.send(JSON.stringify({type: "fps", key: String(v)}))
}

// 修改质量
const changeQuality = (v) => {
    if (!wsSendCmd.value) return ElMessage.error("未启动");
    wsSendCmd.value.send(JSON.stringify({type: "quality", key: String(v)}))
}



// 初始化启动本机客户端
const startVPN = () => {
    if (!!userId) return ElMessage.error("用户ID未设置");
    startVpnApi().then(res => {
        if (res.code === 0) {
            getList();
        }
    })
}

// 发送控制指令websocket
const sendCmdConnect = () => {
    try {
        // 创建 WebSocket 连接
        wsSendCmd.value = new WebSocket(`ws://${import.meta.env.VITE_VPN_SERVER_URL}/control-put?control=${currentItem.value.user_id}&userId=${userId}`)

        wsSendCmd.value.onopen = () => {
            status.value = '已连接'
            isConnected.value = true
            console.log('sendCmd 连接已建立')
        }
    } catch (error) {
        console.error('创建 sendCmd 连接失败:', error)
    }
}

// 获取被控制对象的屏幕截图
const screenConnect = () => {
    try {
        // 创建 WebSocket 连接
        ws.value = new WebSocket(`ws://${import.meta.env.VITE_VPN_SERVER_URL}/frame-get?control=${currentItem.value.user_id}&userId=${userId}`)

        ws.value.onopen = () => {
            status.value = '已连接'
            isConnected.value = true
            console.log('WebSocket 连接已建立')
        }

        ws.value.onmessage = (event) => {
            // 假设是图片数据，可以直接转换为base64（但要注意性能）
            const reader = new FileReader();
            reader.onload = (e) => {
                screenImg.value = e.target.result;
            };
            reader.readAsDataURL(event.data);
        }

        ws.value.onclose = (event) => {
            status.value = '已断开'
            isConnected.value = false
            console.log('WebSocket 连接已关闭:', event)
        }

        ws.value.onerror = (error) => {
            status.value = '连接错误'
            isConnected.value = false
            console.error('WebSocket 错误:', error)
        }

    } catch (error) {
        console.error('创建 WebSocket 连接失败:', error)
    }
}

const disconnect = () => {
    if (ws.value) {
        ws.value.close()
        ws.value = null
    }
    if (wsSendCmd.value) {
        wsSendCmd.value.close()
        wsSendCmd.value = null
    }
}

const listenKeyboard = () => {
    document.addEventListener('keydown', async (event) => {
        if (!mouseIN.value) return
        let keyMsg = {type: 'keyboard', key: event.key.toLowerCase()};
        event.preventDefault()
        const keyData = {
            key: event.key.toLowerCase(),
            modifiers: {
                ctrl: event.ctrlKey,
                alt: event.altKey,
                shift: event.shiftKey,
                meta: event.metaKey
            }
        }
        wsSendCmd.value.send(JSON.stringify(keyMsg))
    })
}

// 组件挂载时自动连接
onMounted(async () => {
    startVPN();

    if (!timer) {
        timer = setInterval(() => {
            getList()
        }, 10000);
    }
})

onBeforeRouteLeave(() => {
    if (timer) clearInterval(timer)
})

// 组件卸载时断开连接
onUnmounted(() => {
    disconnect();
    if (timer) {
        clearInterval(timer);
        timer = null;
    }
})


// 关闭
const closeDialog = () => {
    stopShare(currentItem)
    setTimeout(getList, 2000)
}

const stopShare = (item) => {
    if (!wsSendCmd.value) return ElMessage.error("未启动");
    wsSendCmd.value.send(JSON.stringify({type: 'stop', key: item.user_id}))
    disconnect();
    currentItem.value = null;
}

const startShare = (item) => {
    if (item.control_by && item.control_by !== userId) return ElMessage.error("其他人正在使用!");
    if (!currentItem.value) {
        currentItem.value = item;
        isLoading.value = true;
        screenConnect()
        sendCmdConnect()
        setTimeout(function () {
            isLoading.value = false;
            wsSendCmd.value.send(JSON.stringify({type: 'start', key: item.user_id}))
            // listenKeyboard();
            setTimeout(getList, 2000)
        }, 1000)
    }
    showScreen.value = true;
}

// 拉取电脑列表
const getList = () => {
    listVpnApi().then(res => {
        tableData.value = res.data
    })
}
</script>
<style scoped>
.show-screen {
    margin: 0;
    padding: 0;
    width: 100%;
    font-size: 0;
    min-height: 300px;
    background: #343434;

    img {
        max-width: 100%;
    }
}

</style>
